package com.itheima.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.BookMapper;
import com.itheima.pojo.Book;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.vo.BookVo;
import com.itheima.service.BookService;
import com.itheima.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;

    @Override
    public PageBean<BookVo> list(Integer pageNum, Integer pageSize, Integer categoryId, Integer bookshelfId, String name) {
        PageBean<BookVo> pageBean = new PageBean<>();
        // 设置分页参数默认值
        if (pageNum == null) pageNum = 1; // 默认第一页
        if (pageSize == null) {
            // 如果需要查询所有，将 pageSize 设置为一个非常大的值
            // 注意：实际项目中应避免使用 Integer.MAX_VALUE，可以设置一个合理的上限，如 10000
            pageSize = Integer.MAX_VALUE;
        }
            PageHelper.startPage(pageNum,pageSize);
            List<BookVo> bookVoList = bookMapper.list(categoryId, bookshelfId, name);
            Page<BookVo> bookVoPage= (Page<BookVo>)bookVoList;
            pageBean.setTotal(bookVoPage.getTotal());
            pageBean.setItems(bookVoPage.getResult());
            return pageBean;


    }

    @Override
    public void addBook(Book book) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId =(Integer) map.get("id");
        book.setCreateTime(LocalDateTime.now());
        book.setUpdateTime(LocalDateTime.now());
        book.setCreateUser(userId);
        bookMapper.addBook(book);
    }

    @Override
    public void updateBook(Book book) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        book.setCreateUser(userId);
        book.setUpdateTime(LocalDateTime.now());
        bookMapper.updateBook(book);
    }

    @Override
    public void deleteBook(Integer id) {
        bookMapper.deleteBook(id);
    }
}
